package com.ccx.coachsite.ui.tutorial;

import com.ccx.coachsite.R;
import com.ccx.coachsite.api.CoachSiteSoftMgrApiAccessor;
import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.bus.TutorialInfo;
import com.ccx.coachsite.bus.TutorialProvider;
import com.ccx.coachsite.downloadmgr.DownloadTool;
import com.ccx.coachsite.model.SoftShareMessage;
import com.ccx.coachsite.ui.login.LoginHelper;
import com.ccx.coachsite.util.OpenShareTool;
import com.ccx.coachsite.util.SharedPreferencesUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class TutorialDetailActivity extends Activity {

	private TutorialInfo tutorialInfo;
	private TextView txtTopTitle, txtTitle;
	private ImageButton btnReturn;
	private Button btnDownload, btnFavour, btnShare, btnBack;
	private FrameLayout rootLayout;
	private WebView webContent;
	private ProgressDialog waitingDialog;
	private ProgressBar webProgressBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.tutorial_detail);
		webProgressBar = (ProgressBar) findViewById(R.id.toturial_web_progress_bar);
		rootLayout = (FrameLayout) findViewById(R.id.root);
		txtTopTitle = (TextView) findViewById(R.id.login_top_title);
		btnReturn = (ImageButton) findViewById(R.id.login_btn_return);
		btnReturn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				TutorialDetailActivity.this.finish();
			}
		});
		btnDownload = (Button) findViewById(R.id.tutorial_button_download);
		btnFavour = (Button) findViewById(R.id.tutorial_button_favour);
		btnShare = (Button) findViewById(R.id.tutorial_button_share);
		btnBack = (Button) findViewById(R.id.tutorial_detail_back);

		Button btnRefresh = (Button) findViewById(R.id.btn_nodata_reflash);
		Button btnSettings = (Button) findViewById(R.id.btn_nodata_settings);
		btnRefresh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				loadDetail();
			}
		});
		btnSettings.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent("/");
				ComponentName comp = new ComponentName("com.android.settings",
						"com.android.settings.WirelessSettings");
				intent.setComponent(comp);
				intent.setAction("android.intent.action.VIEW");
				startActivity(intent);
			}
		});
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (webContent.canGoBack())
					webContent.goBack();
			}
		});
		tutorialInfo = (TutorialInfo) getIntent().getSerializableExtra(
				"tutorial");
		txtTopTitle.setText(tutorialInfo.getTitle());
		txtTopTitle.setSelected(true);
		loadDetail();
		
		//添加分享点击统计
		int iShareMsgID = getIntent().getIntExtra("ShareCount", -1);
		if (iShareMsgID!=-1){
			CoachSiteSoftMgrApiAccessor.execShareMsgCount(iShareMsgID);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		boolean isExpert = SharedPreferencesUtil.getBoolean(this,
				SharedKey.Shared_Is_Expert);
		if (isExpert)
			btnShare.setText("推荐");
		else
			btnShare.setText("分享");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (webContent.canGoBack()) {
				webContent.goBack();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void loadDetail() {
		switchView(R.id.ll_on_loading);
		QueryTutorialDetailTask task = new QueryTutorialDetailTask();
		task.execute(tutorialInfo.getId());
	}

	private void onLoadSuccess() {
		txtTitle = (TextView) findViewById(R.id.tutorial_detail_title);
		txtTitle.setText(tutorialInfo.getTitle());
		setTitle(tutorialInfo.getTitle());
		
		//修正分享时打开无标题Bug
		if ( txtTopTitle.getText() == null || "".equals(txtTopTitle.getText().toString()) ){
			txtTopTitle.setText(tutorialInfo.getTitle());
			txtTopTitle.setSelected(true);
		}
		
		webContent = (WebView) findViewById(R.id.tutorial_detail_content);
		webContent.getSettings().setJavaScriptEnabled(true);
		webContent.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				webProgressBar.setProgress(progress);
				if (progress >= 100)
					webProgressBar.setVisibility(View.GONE);
				else
					webProgressBar.setVisibility(View.VISIBLE);
			}
		});
		webContent.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				webContent.loadUrl(url);
				return true;
			}
		});
		webContent.loadUrl(tutorialInfo.getContent());
		if (tutorialInfo.getApkId() < 0)
			btnDownload.setVisibility(View.GONE);
		btnDownload.setOnClickListener(btnDownloadOnClickListener);
		btnFavour.setOnClickListener(btnFavourOnClickListener);
		btnShare.setOnClickListener(btnShareOnClickListener);
		if (tutorialInfo.isFavour())
			btnFavour.setText("已收藏");
		else
			btnFavour.setText("收藏");
		switchView(R.id.tutorial_detail_root);
	}

	private void onLoadFail() {
		switchView(R.id.ll_no_data);
	}

	private void switchView(int id) {
		for (int i = 0; i < rootLayout.getChildCount(); i++) {
			View view = rootLayout.getChildAt(i);
			if (view.getId() == id)
				view.setVisibility(View.VISIBLE);
			else
				view.setVisibility(View.GONE);
		}
	}

	private void onCollectSuccess() {
		if (waitingDialog != null) {
			waitingDialog.dismiss();
			waitingDialog = null;
		}
		btnFavour.setText("已收藏");
		tutorialInfo.setFavour(true);
		Toast.makeText(this, "已加入收藏", Toast.LENGTH_SHORT).show();
	}

	private void onCollectFail() {
		if (waitingDialog != null) {
			waitingDialog.dismiss();
			waitingDialog = null;
		}
		Toast.makeText(this, "对不起，收藏失败，请重试", Toast.LENGTH_SHORT).show();
	}

	OnClickListener btnDownloadOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			DownloadTool.downSoftItemByID(TutorialDetailActivity.this,
					tutorialInfo.getApkId());
		}
	};

	OnClickListener btnFavourOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!LoginHelper.requireLogin(TutorialDetailActivity.this))
				return;

			if (tutorialInfo.isFavour()) {
				Toast.makeText(TutorialDetailActivity.this, "此教程已收藏",
						Toast.LENGTH_SHORT).show();
				return;
			}
			waitingDialog = new ProgressDialog(TutorialDetailActivity.this);
			waitingDialog.setMessage("请稍候..");
			waitingDialog.show();
			FavourTask task = new FavourTask();
			task.execute(0);
		}
	};

	OnClickListener btnShareOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!LoginHelper.requireLogin(TutorialDetailActivity.this))
				return;

			String softFlag = DownloadTool.getSoftFlag(getIntent().getStringExtra(DownloadTool.SOFT_FLAG));
			OpenShareTool.showOperDialog(TutorialDetailActivity.this,
					tutorialInfo.getTitle(), "", tutorialInfo.getId() + "",
					SoftShareMessage.TYPE_TUTORIAL_SHARE_TYPE,
					tutorialInfo.getCategory(), softFlag);
		}
	};

	class QueryTutorialDetailTask extends AsyncTask<Integer, Integer, Boolean> {

		private String errorMessage;

		public String getErrorMessage() {
			return errorMessage;
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			return TutorialProvider.getInstance().loadDetail(
					TutorialDetailActivity.this, tutorialInfo);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result)
				onLoadSuccess();
			else
				onLoadFail();
		}
	}

	class FavourTask extends AsyncTask<Integer, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Integer... params) {
			return TutorialProvider.getInstance().collectFavour(
					TutorialDetailActivity.this, tutorialInfo);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result)
				onCollectSuccess();
			else
				onCollectFail();
		}
	}
}
